#!/bin/bash

#Variables locales
datos="$grupo/data"
recibidos="$grupo/recibidos"
procesados="$grupo/procesados"
nuevos="$grupo/nuevos"
archbenef="$datos/beneficios.mae"

#Verificamos si ya está corriendo
cmd_name=`basename "$0"`
pid=`pidof -x $cmd_name`
proc_count=`ps -C $cmd_name | sed 1d | grep -c ""`
if [ $proc_count -gt 2 ]
then
    echo "El proceso $cmd_name ya se encuentra corriendo. Espere a que finalice."
    exit 1
fi

echo "Proceso iniciado con PID: $pid ."

#ver si se inicializó el ambiente
checkPostiniExecuted() {
	if [ "$POSTINI_EXECUTED" != "true" ]
	then
		echo "Debe ejecutar el comando 'postini.sh' antes de correr este comando. "
		exit 1
	fi
}
checkPostiniExecuted

 
field_names=( 
    "Cuil"
    "Tipo doc" 
    "Nro doc" "Apellido" 
    "Nombre" 
    "Domicilio" 
    "Localidad" 
    "Provincia" 
    "Código de beneficio" 
)

field_validations=( 
    "^[0-9]\{11,11\},"
    "^[^,]*,[DLP][UCEA]," 
    "^[^,]*,[^,]*,[A-Za-z0-9]\{9,9\},"
    "^[^,]*,[^,]*,[^,]*,[A-Za-z0-9]\{1,\}," 
    "^[^,]*,[^,]*,[^,]*,[^,]*,[A-Za-z0-9]\{1,\}," 
    "^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[A-Za-z0-9]\{1,\}," 
    "^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[A-Za-z0-9]\{1,\}," 
    "^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[A-Za-z0-9]\{1,\}," 
    "^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[A-Za-z0-9]\{5,5\}" 
)

optional_field_names=( 
    "FPA" 
    "DP" 
)

optional_field_validations=(
    "^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[0-9]\{4,4\}-[0-1][0-9]-[0-3][0-9]" 
    "^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[1-9]*$" 
)

#Devuelve el máximo de los parametros pasados
max()
{
    max=$1
    params=$@
    for (( i=1; i<=$#; i++ )); do
        if [[ "$max" < "${params[${i}]}" ]]
        then
            max=${params[${i}]}
        fi
    done 
    echo $max
}

#Devuelve el mínimo de los parametros pasados
min()
{
echo $1
    min=$1
    params=$@
    for (( i=1; i<=$#; i++ )); do
        if [[ "$min" > "${params[${i}]}" ]]
        then
            min=${params[${i}]}
        fi
    done 
    echo $min
}

#Inicializamos el log
files_to_proc=`ls "$recibidos" | grep -c ""`
gralog.sh "$cmd_name" "-I" "Inicio de Postular: $files_to_proc"

#Procesamos cada archivo
for file in `ls $recibidos`
do
    agency=`echo $file | sed "s/\.[0-9]*$//"`
    secuence=`echo $file | sed "s/^[0-9]*\.//"`
    reg_error=0
    reg_success=0
    total_regs=0

    gralog.sh "$cmd_name" "-I" "Archivo a Procesar: $file"
    for register in `cat "$recibidos/$file"`
    do
        fields=`echo $register | tr "," "\n"`
        fields_count=`echo $register | tr "," "\n" | grep -c ""`
        
        #validamos a nivel registro
        if [ $fields_count -lt 9 ] || [ $fields_count -gt 11 ]
        then
            echo "$agency,$secuence,$total_regs,formato de registro erróneo,$register" >> "$nuevos/benerro.$pid"
            reg_error=`echo "$reg_error + 1" | bc`
        else
            failure=0
            
            #validamos forma de campos obligatorios
            for (( i=0; i<${#field_names[@]}; i++ )); do
                if [ `echo $register | grep "${field_validations[${i}]}" >> /dev/null; echo $?` -ne 0 ]
                then
                    echo "$agency,$secuence,$total_regs,campo ${field_names[${i}]} no informado,$register" >> "$nuevos/benerro.$pid"
                    failure=1
                    break
                fi
            done 
            
            #validamos forma de campos opcionales
            if [ $failure -ne 1 ]
            then
                for (( i=0; i<${#optional_field_names[@]}; i++ )); do
                    if [ $fields_count -gt `echo "9 + $i" | bc` ] && [ `echo $register | grep "${optional_field_validations[${i}]}" >> /dev/null; echo $?` -ne 0 ]
                    then
                        echo "$agency,$secuence,$total_regs,${optional_field_names[${i}]} invalida,$register" >> "$nuevos/benerro.$pid"
                        failure=1
                        break
                    fi
                done 
            fi

            #validamos los valores de los campos
            if [ $failure -ne 1 ]
            then
                cod_benef=`echo $register | sed "s/^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,\([A-Za-z0-9]\{5,5\}\).*/\1/"`
                if [ `cat $archbenef | grep "^[^,]*,$cod_benef," >> /dev/null; echo $?` -eq 1 ]
                then
                    echo "$agency,$secuence,$total_regs,no existe el beneficio,$register" >> "$nuevos/benerro.$pid"
                    failure=1
                else
                    benef=`cat $archbenef | grep "^[^,]*,$cod_benef," | head -n1`
                    if [ $fields_count -gt 9 ]
                    then
                        FPA=`echo $register | sed "s/^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,\([0-9]\{4,4\}-[0-1][0-9]-[0-3][0-9]\).*/\1/"`
                        if [ $fields_count -gt 10 ]
                        then
                            DP=`echo $register | sed "s/^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,\([1-9]*\)$/\1/"`
                        else
                            DP=""
                        fi
                    else
                        FPA=""
                        DP=""
                    fi
                    FFB=`echo $benef | sed "s/^[^,]*,[^,]*,[^,]*,[^,]*,\([^,]*\).*/\1/"`
                    DMB=`echo $benef | sed "s/^[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,\([^,]*\)$/\1/"`
                    if [ "$FPA" != "" ] && [[ "$FPA" > "$FFB" ]]
                    then
                        status="rechazado"
                        cause="FPA mayor FFB"
                    elif [ "$DP" != "" ] && [[ "$DP" > "$DMB" ]]
                    then
                        status="rechazado"
                        cause="FPA mayor FFB"
                    fi
                fi
            fi

            if [ $failure -eq 1 ]
            then
                reg_error=`echo "$reg_error + 1" | bc`
            else
                FC=`date +%Y-%m-%d`
                FIB=`echo $benef | sed "s/^[^,]*,[^,]*,[^,]*,\([^,]*\).*/\1/"`
                FEA=`max "$FC" "$FPA" "$FIB"`
                if [ "$status" != "rechazado" ]
                then
                    reg_success=`echo "$reg_success + 1" | bc`
                    if [[ "$FEA" > "$FC" ]]
                    then
                        status="pendiente"
                        cause=""
                    else
                        status="aprobado"
                        cause=""
                    fi
                else
                    reg_error=`echo "$reg_error + 1" | bc`
                fi
                if [ "$DP" == "" ]
                then
                    DP=$DMB
                fi

                FF_month=`echo $FEA | sed "s/[0-9]\{4,4\}-\([0-1][0-9]\)-[0-3][0-9]/\1/"`
                FF_year=`echo $FEA | sed "s/\([0-9]\{4,4\}\)-[0-1][0-9]-[0-3][0-9]/\1/"`
                FF_month=`echo "$FF_month + $DP" | bc`
                FF_year=`echo "$FF_year + ($FF_month / 12)" | bc`
                FF_month=`echo "$FF_month % 12" | bc`
                FF_month=`printf "%02d" "$FF_month"`
                FF=`echo $FEA | sed "s/[0-9]\{4,4\}-[0-1][0-9]-\([0-3][0-9]\)/$FF_year-$FF_month-\1/"`
                FF=`min "$FF" "$FFB"`

                #grabamos el registro de nuevo beneficiario
                mandatory_fields=`echo $register | sed "s/^\([^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*,[^,]*\).*/\1/"`
                user=`whoami`
                echo "$agency,$secuence,$mandatory_fields,$FPA,$FEA,$status,$DP,$FF,$cause,$user,$FC" >> "$nuevos/benef.$pid"
            fi
        fi
        total_regs=`echo "$total_regs + 1" | bc`
    done
    mover.sh "$recibidos/$file" "$procesados" "$cmd_name"

    gralog.sh "$cmd_name" "-I" "Cantidad Total de registros: $total_regs"
    gralog.sh "$cmd_name" "-I" "Cantidad de registros con error: $reg_error"
    gralog.sh "$cmd_name" "-I" "Cantidad de beneficiarios nuevos: $reg_success"
done

#Cerramos el log
gralog.sh "$cmd_name" "-I" "Fin de Postular"
